package org.csc.sss.core.security;

import lombok.extern.slf4j.Slf4j;
import org.csc.sss.core.model.SysPermission;
import org.csc.sss.core.model.SysUser;
import org.csc.sss.core.repository.SysUserRepository;
import org.csc.sss.core.repository.impl.SysUserRepositoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomUserService implements UserDetailsService {

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysUserRepositoryImpl sysUserRepositoryImpl;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = sysUserRepository.findBynickname(username);
        if (null == user) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysPermission> permissions = sysUserRepositoryImpl.permissions(user.getId());
        if (null != permissions && !permissions.isEmpty()) {
            for (SysPermission sysPermission : permissions) {
                authorities.add(new SimpleGrantedAuthority(sysPermission.getName()));
            }
        }
        SecurityUser securityUser = new SecurityUser(user, authorities);
        return securityUser;
    }
}
